package binarytree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/19 11:45
 * https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
 * 填充它的每个 next 指针，让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点，则将 next 指针设置为 NULL。
 */
public class Connect {

    class Node {
        int val;
        Node left;
        Node right;
        Node next;

        public Node() {
        }

        public Node(int val) {
            this.val = val;
        }

        public Node(int val, Node left, Node right, Node next) {
            this.val = val;
            this.left = left;
            this.right = right;
            this.next = next;
        }
    }

    public Node connect(Node root) {
        Queue<Node> levelNodes = new LinkedList<>();
        if (root != null) {
            levelNodes.offer(root);
        }
        while (!levelNodes.isEmpty()) {
            int size = levelNodes.size();
            for (int i = 0; i < size; i++) {
                Node poll = levelNodes.poll();
                if (i + 1 == size) {
                    poll.next = null;
                }else{
                    poll.next = levelNodes.peek();
                }
                if (poll.left != null) {
                    levelNodes.offer(poll.left);
                }
                if (poll.right != null) {
                    levelNodes.offer(poll.right);
                }
            }
        }
        return root;
    }

    public static void main(String[] args) {

    }
}
